import Vue from "vue";
import Vuex from 'vuex';

Vue.use(Vuex)

const store = new Vuex.Store({
  strict: process.env.NODE_ENV === 'development',
  state: {
    // list: [{
    //   id: 100,
    //   name: "吃饭",
    //   isDone: true
    // },
    // {
    //   id: 201,
    //   name: "睡觉",
    //   isDone: false
    // },
    // {
    //   id: 103,
    //   name: "打豆豆",
    //   isDone: true
    // },
    // ],
    list: JSON.parse(localStorage.getItem('todoList')) || [],
    type: 'all',
  },

  mutations: {
    //切换分类
    changeType(state, type) {
      state.type = type
    },
    //添加元素
    addItem(state, value) {
      state.list.push({
        id: +new Date(),
        name: value,
        isDone: false
      })
    },
    //删除元素
    delItem(state, id) {
      state.list = state.list.filter(item => item.id !== id)
    }
    ,
    //清除已完成
    clear(state) {
      state.list = state.list.filter(item => !item.isDone)
    },
    //切换元素选中状态
    changeDone(state, id) {
      state.list.find(item => {
        if (item.id === id) {
          item.isDone = !item.isDone
        }
      })
    },
    //全选切换
    changeAll(state, { newList, val }) {
      newList = newList.forEach(item => item.isDone = val)
    }
  },
  actions: {
    //异步函数封装上面的clear
    clearAsync(contxet) {
      setTimeout(() => {
        contxet.commit('clear')
      }, 1000)
    }
  },

  getters: {
    //类型切换后的数据分类
    newList(state) {
      if (state.type === 'all') {
        return state.list
      }
      else if (state.type === 'No') {
        return state.list.filter(item => !item.isDone)
      }
      else {
        return state.list.filter(item => item.isDone)
      }
    },
  },
  modules: {
  }
})

export default store